﻿using System;
using System.Timers;
/*
 * c2. 使用事件机制，模拟实现一个闹钟功能。
 * 闹钟可以有嘀嗒（Tick）事件和响铃（Alarm）两个事件。
 * 在闹钟嘀嗒运行时或者响铃时，在控制台显示提示信息。
 */
namespace HW3_2
{
    public delegate void TickEventHandler(object sender, TickEventArg tickEventArg);
    public delegate void AlarmEventHandler(object sender, EventArgs eventArgs);

    public class TickEventArg : EventArgs//事件床
    {
        public int checkPoint;

        public TickEventArg(int checkPoint)
        {
            this.checkPoint = checkPoint;
        }
    }

    class Clock
    {
        public event TickEventHandler Tick;
        public event AlarmEventHandler Alarm;

        public int CheckPoint
        {
            set
            {
                if (value > 0)
                {
                    checkPoint = value;
                    checkCount = 0;
                }
            }
        }

        private readonly System.Timers.Timer timer;
        private int checkPoint;
        private int checkCount;

        public Clock()
        {
            checkCount = 0;
            timer = new System.Timers.Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(Check);
            timer.AutoReset = true;
        }

        public void Start()
        {
            timer.Start();
            Console.WriteLine("Timer----has Started!");
        }

        public void Close()//没有调用机会
        {
            timer.Stop();
            Console.WriteLine("Timer----will close");
        }

        private void Check(object sender, System.Timers.ElapsedEventArgs e)
        {
            checkCount += 1;
            Tick(this, new TickEventArg(checkCount));
            if (checkCount == checkPoint)
            {
                Alarm(this, new EventArgs());
                checkPoint = -1;
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Random rd = new Random();
                int a = rd.Next(1, 6);
                Clock clock = new Clock();  // 带倒计时功能的时钟
                clock.Alarm += (S, E) => { Console.WriteLine("Alarmed!"); };
                clock.Tick += (S, E) => { Console.WriteLine($"Time: {DateTime.Now:hh:mm:ss}"); };
                clock.CheckPoint = a;
                clock.Start();

                Console.Read();
            }
        }
    }
}
